﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Ams.Mvc.Bootstrap.Annotations
{
    public class RegExValidator<TDataAnnotation> : DataAnnotationsModelValidator<TDataAnnotation> where TDataAnnotation : RegularExpressionAttribute
    {
        private readonly string _message;
        private readonly string _pattern;

        public RegExValidator(ModelMetadata metadata, ControllerContext context, TDataAnnotation attribute)
            : base(metadata, context, attribute)
        {
            _pattern = attribute.Pattern;
            _message = attribute.ErrorMessage;
        }

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = _message,
                ValidationType = "regex"
            };

            rule.ValidationParameters.Add("pattern", _pattern);

            return new[] { rule };
        }
    }
}